package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"perm-guard/cache"
	"perm-guard/models"
	"perm-guard/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data).Limit(20)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := models.RoleNode{
		Nid: nid,
		Rid: rid,
	}
	models.DB.Create(&data).Limit(20)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	/*
			SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	var roles []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Find(&roles)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": roles,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	/*
				SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/
	var nodes []models.Node
	models.DB.Table("nodes").
		Joins(" LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid = ?", rid).
		Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": nodes,
	})
	return
}
func GoodAdd(c *gin.Context) {
	goodname := c.PostForm("goodname")
	goodnum := c.PostForm("goodnum")
	goodprice := c.PostForm("goodprice")
	data := models.Good{
		GoodName:  goodname,
		GoodNum:   goodnum,
		GoodPrice: goodprice,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func OrderAdd(c *gin.Context) {
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	form_address := c.PostForm("form_address")
	to_address := c.PostForm("to_address")
	data := models.Order{
		Gid:          gid,
		Form_Address: form_address,
		To_Address:   to_address,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	/*
			SELECT
		  orders.id AS Oid,
		  orders.form_address AS Form_Address,
		  orders.to_address AS To_Address,
		  goods.good_name AS GoodName,
		  goods.good_num AS GoodNum,
		  goods.good_price AS GoodPrice
		FROM
		  orders
		  LEFT JOIN goods ON orders.gid = goods.id
	*/
	var orderlist []models.OrderList
	redis_key := "orderlist_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select("orders.id AS Oid",
				"orders.form_address AS Form_Address",
				"orders.to_address AS To_Address",
				"goods.good_name AS GoodName",
				"goods.good_num AS GoodNum",
				"goods.good_price AS GoodPrice").
			Joins("LEFT JOIN goods ON orders.gid = goods.id").
			Offset(offset).Limit(size).
			Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	var total int64
	models.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  orderlist,
		"total": total,
	})
}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
			SELECT
		  orders.id AS Oid,
		  orders.form_address AS Form_Address,
		  orders.to_address AS To_Address,
		  goods.good_name AS GoodName,
		  goods.good_num AS GoodNum,
		  goods.good_price AS GoodPrice
		FROM
		  orders
		  LEFT JOIN goods ON orders.gid = goods.id
			Where orders.id= 1
	*/
	var orderlist []models.OrderList
	redis_key := "orderlist_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select("orders.id AS Oid",
				"orders.form_address AS Form_Address",
				"orders.to_address AS To_Address",
				"goods.good_name AS GoodName",
				"goods.good_num AS GoodNum",
				"goods.good_price AS GoodPrice").
			Joins("LEFT JOIN goods ON orders.gid = goods.id").
			Where("orders.id=?", id).
			Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	var total int64
	models.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  orderlist,
		"total": total,
	})
}
